package com.hand.wfive.activity.sign

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.graphics.PorterDuff
import android.graphics.PorterDuffColorFilter
import android.graphics.drawable.LayerDrawable
import android.widget.SeekBar
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.qmuiteam.qmui.arch.SwipeBackLayout
import com.hand.wfive.App
import com.hand.wfive.R
import com.hand.wfive.adapter.SignatureWriteColorAdapter
import com.hand.wfive.base.BaseActivity
import com.hand.wfive.entity.FileModel
import com.hand.wfive.entity.Params
import com.hand.wfive.loginAndVip.UserManager
import com.hand.wfive.util.FileUtils
import com.hand.wfive.util.ImageUtils
import com.hand.wfive.util.click.NoFastClickUtils
import com.hand.wfive.util.click.singleClick
import com.hand.wfive.util.oss.OssCallBack
import com.hand.wfive.util.oss.OssRequest
import com.hand.wfive.view.InputDialog
import kotlinx.android.synthetic.main.activity_signature_write.*
import org.jetbrains.anko.contentView
import org.jetbrains.anko.toast
import kotlin.concurrent.thread

@SuppressLint("ClickableViewAccessibility")
class SignatureWriteActivity : BaseActivity() {

    companion object {
        fun showIntent(context: Context, flag: Int = 1): Intent {
            val intent = Intent(context, SignatureWriteActivity::class.java)
            intent.putExtra(Params.flag, flag)
            return intent
        }
    }

    private var mFlag = -1

    override fun getContentViewId() = R.layout.activity_signature_write

    override fun init() {
        if (contentView is SwipeBackLayout) {
            (contentView as SwipeBackLayout).isEnableSwipeBack = false
        }

        mFlag = intent.getIntExtra(Params.flag, mFlag)

        // 取消
        qtv_cancel.singleClick { finish() }
        // 完成
        qtv_complete.singleClick { onComplete() }
        // 签名改变
        paint_view.setStepCallback {
            tv_tips.isVisible = !paint_view.canUndo()
        }
        paint_view.setOnTouchListener { _, _ ->
            if (paint_view.canUndo()) {
                tv_tips.isVisible = false
            }
            false
        }
        // 清除
        qtv_clear.singleClick { paint_view.reset() }
        // 画笔大小
        sb_size.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onStartTrackingTouch(seekBar: SeekBar?) = Unit
            override fun onProgressChanged(
                seekBar: SeekBar?, progress: Int, fromUser: Boolean
            ) = Unit

            override fun onStopTrackingTouch(seekBar: SeekBar?) {
                paint_view.setPaintWidth(sb_size.progress + 5)
            }
        })
        // 颜色
        val adapter = SignatureWriteColorAdapter()
        adapter.setOnItemClickListener { _, _, position ->
            if (NoFastClickUtils.isFastClick()) return@setOnItemClickListener
            updateColor(adapter.getItem(position))
        }
        recycler_color.layoutManager =
            LinearLayoutManager(mActivity, RecyclerView.HORIZONTAL, false)
        recycler_color.adapter = adapter
        updateColor(adapter.getItem(adapter.itemCount - 1))
    }

    private fun updateColor(color: Int) {
        paint_view.paintColor = color
        (sb_size.progressDrawable as LayerDrawable).getDrawable(2).colorFilter =
            PorterDuffColorFilter(color, PorterDuff.Mode.SRC)
        sb_size.thumb.colorFilter =
            PorterDuffColorFilter(color, PorterDuff.Mode.SRC_ATOP)
        sb_size.invalidate()
    }

    private fun onComplete() {
        if (paint_view.isEmpty) {
            showNormalTip("您还没有签名")
            return
        }
        if (mFlag == 1) {
            showLoadingTipC()
            thread {
                val path = ImageUtils.saveBitmapPNG(
                    mContext, paint_view.bitmap, App.getContext().cacheTempPath
                )
                runOnUiThread {
                    dismissTip()
                    saveSuccess(path)
                }
            }
            return
        }
        val value = FileUtils.getRandomFileName()
        loadSignatureImage("${value}.png")
        //弹窗由用户反馈输入名字后保存，签字没了，保存的是空白图片
        /*InputDialog(mContext, "文件名", "请输入签名文件名") { dialog, value ->
            if (value.isEmpty()) {
                toast("请输入签名文件名！")
                return@InputDialog
            }
            dialog.dismiss()
            loadSignatureImage("${value}.png")
        }.show()*/
    }

    private fun loadSignatureImage(fileName: String) {
        showLoadingTipC("正在保存签名文件")
        thread {
            val model = FileModel()
            model.type = Params.fileTypeSign
            model.fileName = fileName
            model.fileId = "${UserManager.getInstance().userId}/${Params.fileTypeSign}/${
                System.currentTimeMillis()
            }${model.fileName.replace(",", "")}"
            model.filePath = ImageUtils.saveBitmapPNG(
                mContext, paint_view.bitmap, App.getContext().cacheTempPath, fileName
            )
            model.size = FileUtils.getFileSize(model.filePath)
            runOnUiThread {
                if (model.size <= 0) {
                    showNormalTip("保存签名失败")
                } else {
                    OssRequest.getInstance().uploadFile(model, object : OssCallBack {
                        override fun onSuccess() {
                            dismissTip()
                            toast("保存成功~")
                            saveSuccess(model.filePath)
                        }

                        override fun onFailure(msg: String) {
                            showNormalTip(msg.ifEmpty { "保存签名失败" })
                        }
                    })
                }
            }
        }
    }

    private fun saveSuccess(path: String) {
        val resultIntent = Intent()
        resultIntent.putExtra(Params.path, path)
        resultIntent.putExtra(Params.flag, mFlag)
        resultIntent.putExtra(Params.type, Params.fileTypeSign)
        setResult(RESULT_OK, resultIntent)
        finish()
    }
}